<template>
  <d2-container>
	  <template slot="header">
		  <el-button type="primary" @click="change">新 增</el-button>
		  <el-button
		    type="primary"
		    plain
		    @click="openUser"
		  >用 户 授 权</el-button>
		  <el-button
		    type="primary"
		    plain
		    @click="openAuth"
		  >功 能 授 权</el-button>
	  </template>
    <template>

      <el-table stripe border :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column fixed prop="roleName" label="角色名称" width="200"></el-table-column>
        <el-table-column fixed prop="roleCode" label="角色编码" width="200"></el-table-column>
        <el-table-column
          prop="valid"
          label="Valid"
          :filters="[{ text: '无效', value: 0}, { text: '有效', value: 1 }]"
          :filter-method="filterValid"
          filter-placement="bottom-end"
        >
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.valid === 1 ? 'primary' : 'success'"
              disable-transitions
            >{{scope.row.valid==0?"无效":"有效"}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed prop="description" label="角色描述" width="200"></el-table-column>
        <el-table-column prop="reviseTime" label="更新时间" :formatter="forDate"></el-table-column>
        <el-table-column fixed="right" label="操作" width="180">
          <template slot-scope="scope">
            <el-button type="primary" size="small" @click="updateRow(scope.row.id)">编辑</el-button>
            <el-button
              @click.native.prevent="deleteRow(scope.$index, tableData)"
              size="small"
            >移除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <template>
      <div>
        <keep-alive>
          <addPage
            :addPage="addComponent"
            @on-addPage-change="onAddPageChange"
            @on-loadlist-change="fetchData"
          ></addPage>
        </keep-alive>
      </div>
      <div>
        <keep-alive>
          <updatePage
            @on-loadlist-change="fetchData"
            :uShow="updateComponent"
            @on-uShow-change="onUShowChange"
            :uId="updateId"
            @on-id-change="onIdChange"
          ></updatePage>
        </keep-alive>
      </div>
    </template>
		<template slot="footer">
			<div class="page">
        <el-pagination
		  background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50,100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
    </template>
    <!-- 角色授权-->
    <template>
      <el-dialog title="功能授权" :visible.sync="permissionDisplay" :before-close="handleClose">
        <el-main>
          <el-tree
            :data="treeNode"
            :props="defaultProps"
            ref="tree"
            node-key="id"
            highlight-current
            :check-strictly="false"
            show-checkbox
            :render-content="renderContent"
          ></el-tree>
        </el-main>
        <el-footer>
          <el-button type="primary" @click="submitAuthRole">确 定</el-button>
          <el-button @click="permissionDisplay=false">取 消</el-button>
        </el-footer>
      </el-dialog>
      <template>
        <!-- 用户授权-->
      </template>
      <el-dialog title="用户授权" :visible.sync="userDisplay" :before-close="handleClose">
        <el-main>
          <el-table
            :data="userTableData"
            style="width: 100%"
            ref="userTable"
            @selection-change="handleSelectionChangeUser"
          >
            <el-table-column type="selection"></el-table-column>
            <el-table-column prop="userName" label="用户名"></el-table-column>
          </el-table>
        </el-main>
        <el-footer>
          <el-button type="primary" @click="submitAuthUser">确 定</el-button>
          <el-button @click="userDisplay=false">取 消</el-button>
        </el-footer>
      </el-dialog>
    </template>
  </d2-container>
</template>

<script>
import {
  RoleList,
  DelRole,
  AuthRole,
  GetAuthById,
  GetAllUser,
  AuthUserr,
  FindByRoleId,
  GetTreeNode
} from '@api/role/role'
import addPage from './add'
import updatePage from './update'
import dayjs from 'dayjs'
import user from '../../../store/modules/d2admin/modules/user'

export default {
  name: 'system-role',
  components: {
    addPage,
    updatePage
  },
  data () {
    return {
      addComponent: false,
      updateComponent: false,
      permissionDisplay: false,
      userDisplay: false,
      updateId: 0,
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      multipleSelection: [],
      multipleSelectionUser: [],
      // tree
      treeNode: [],
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      // permissionList: [],
      permissionIds: [],
      userTableData: []
    }
  },

  mounted () {
    this.fetchData()
  },
  methods: {
    /** 双向绑定 start */
    change () {
      this.addComponent = !this.addComponent
    },
    onAddPageChange (val) {
      this.addComponent = val // ④外层调用组件方注册变更方法，将组件内的数据变更，同步到组件外的数据状态中
    },
    uChange () {
      this.updateComponent = !this.updateComponent
    },
    onUShowChange (val) {
      this.updateComponent = val // ④外层调用组件方注册变更方法，将组件内的数据变更，同步到组件外的数据状态中
    },
    idChange (val) {
      this.updateId = val
    },
    onIdChange (val) {
      this.updateId = val // ④外层调用组件方注册变更方法，将组件内的数据变更，同步到组件外的数据状态中
    },
    /** 双向绑定 end */

    fetchData () {
      this.loading = true
      RoleList({
        currentPage: this.currentPage,
        pageSize: this.pageSize
      })
        .then(res => {
          // console.log(res.list)
          this.tableData = res.data.content
          this.total = res.data.total
          this.loading = false
        })
        .catch(err => {
          console.log('err', err)
          this.loading = false
        })
    },
    handleSizeChange (val) {
      // console.log(`每页 ${val} 条`);
      this.pageSize = val
      this.fetchData()
    },
    handleCurrentChange (val) {
      // console.log(`当前页: ${val}`);
      this.currentPage = val
      this.fetchData()
    },
    deleteRow (index, rows) {
      // console.log( rows[index].id)
      // rows.splice(index, 1)

      this.$confirm('确定删除吗')
        .then(() => {
          let id = rows[index].id
          this.loading = true
          DelRole({ roleId: id })
            .then(res => {
              this.fetchData()
              this.loading = false
            })
            .catch(err => {
              console.log('err', err)
              this.loading = false
            }) // function(done)，done 用于关闭 Dialog
          done()
        })
        .catch(() => {
          // console.log("取消操作");
        })
    },
    filterValid (value, row) {
      // console.log(" row = "+JSON.stringify(row))
      return row.valid === value
    },
    updateRow (id) {
      this.uChange()
      this.idChange(id)
    },
    forDate (row, column) {
      return row.reviseTime == null
        ? ''
        : dayjs(row.reviseTime).format('YYYY-MM-DD HH:mm:ss')
    },
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    // 功能授权 窗口 关闭
    handleClose (done) {
      this.$confirm('确定关闭吗')
        .then(() => {
          // function(done)，done 用于关闭 Dialog
          done()
        })
        .catch(() => {
          // console.log("点击确定时触发");
        })
    },
    // 提交 角色授权
    submitAuthRole () {
      let _this = this
      this.loading = true
      let roles = []
      this.multipleSelection.forEach(function (e) {
        roles.push(e.id)
      })
      this.permissionIds = this.$refs.tree.getCheckedKeys()
      this.$refs.tree.getHalfCheckedKeys().forEach(function (e) {
        _this.permissionIds.push(e)
      })
      AuthRole({
        roleIds: roles,
        resourceIds: this.permissionIds
      })
        .then(res => {
          this.$message({
            message: '授权成功',
            type: 'success'
          })
          this.fetchData()
          this.loading = false
          this.permissionDisplay = false
        })
        .catch(err => {
          console.log('err', err)
          this.loading = false
        })
    },
    // 打开 角色授权页面
    openAuth () {
      this.loadTree()
    },
    loadTree () {
      let this_ = this
      let name = user.state.info.name
      GetTreeNode({ loginName: name })
        .then(res => {
          this.treeNode = res.data
          // console.log(this.treeNode)

          this.loading = true
          if (this.multipleSelection.length == 1) {
            GetAuthById({ roleId: this.multipleSelection[0].id })
              .then(res => {
                if (typeof res.data !== 'undefined') {
                  res.data.forEach(function (e) {
                    this_.$refs.tree.setChecked(e.id, true)
                    // console.log(e.id);
                  })
                }

                this.loading = false
              })
              .catch(err => {
                console.log('err', err)
                this.loading = false
              })
            this.permissionDisplay = true
          } else {
            this.$message({
              message: '请选择单项角色进行授权',
              type: 'warning'
            })
          }
        })
        .catch(err => {
          console.log('err', err)
        })
    },
    openUser () {
      if (this.multipleSelection.length == 1) {
        this.loading = true
        GetAllUser()
          .then(res => {
            this.userTableData = res.data

            this.loadUserSelect()
            this.loading = false
          })
          .catch(err => {
            console.log('err', err)
            this.loading = false
          })
        this.userDisplay = true
      } else {
        this.$message({
          message: '请选择单项角色进行授权',
          type: 'warning'
        })
      }
    },
    submitAuthUser () {
      this.loading = true
      let roles = []
      this.multipleSelection.forEach(function (e) {
        roles.push(e.id)
      })
      let users = []
      this.multipleSelectionUser.forEach(function (e) {
        users.push(e.id)
      })
      // console.log("roleIds "+roles+"  userIDs "+JSON.stringify(users));
      AuthUserr({ roleIds: roles, userIds: users })
        .then(res => {
          this.$message({
            message: '授权成功',
            type: 'success'
          })
          this.fetchData()
          this.loading = false
          this.userDisplay = false
        })
        .catch(err => {
          console.log('err', err)
          this.loading = false
        })
    },
    handleSelectionChangeUser (val) {
      this.multipleSelectionUser = val
    },
    // 加载已经分配的权限
    loadUserSelect () {
      this.loading = true
      let this_ = this
      FindByRoleId({ roleId: this.multipleSelection[0].id + '' })
        .then(res => {
          this.multipleSelectionUser = []
          // console.log(this.multipleSelectionUser)
          this.userTableData.forEach(row => {
            res.data.forEach(e => {
              if (row.id === e.id) {
                this_.$refs.userTable.toggleRowSelection(row)
              }
            })
          })
          // tihs.$refs.userTable.
          this.loading = false
        })
        .catch(err => {
          console.log('err', err)
          this.loading = false
        })
    },
    renderContent (h, { node, data, store }) {
      if (data.type == 2) {
        return (
          <span class="custom-tree-node">
            <el-tag style="margin:3px 5px 3px 0;">{node.label}【按钮】</el-tag>
          </span>
        )
      } else {
        return (
          <span class="custom-tree-node">
            <i class="el-icon-tickets"></i><span style="margin-left:5px;">{node.label}</span>
          </span>
        )
      }
    }
  }
}
</script>

<style scoped>
	::v-deep .el-tree-node__content {
		height: auto;
	}
</style>
